//
//  MineViewController.m
//  礼物go
//
//  Created by dllo on 16/5/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "MineViewController.h"
#import "MineBigTableView.h"
#import "TitleViewController.h"
#import "OptionViewController.h"


#import "HotDeatilViewController.h"
#import "SelectDetailViewController.h"

#define headerHeight 200

static NSString *const mineCell = @"mineCell";

static NSString *const GoTopNotificationName = @"goTop";//进入置顶命令
static NSString *const LeaveTopNotificationName = @"leaveTop";//离开置顶命令

@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

@property(nonatomic,strong)MineBigTableView *mineTableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIView *headerView;

@property (nonatomic, assign) BOOL canScroll;

@property(nonatomic,strong)UIImageView *userImageView;
@property(nonatomic,strong)UILabel *userNameLabel;
@property(nonatomic,strong)UIButton *accountButton;
@property(nonatomic,strong)UIImageView *bgImageView;
@property(nonatomic,strong)  NSArray *hotModelArray;
@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"我";
 //self.navigationController.navigationBar.barTintColor = [UIColor redColor];
     self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setup"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction)];
     self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];

    
    
self.mineTableView = [[MineBigTableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHeight - 49 - 64) style: UITableViewStylePlain];
    self.mineTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mineTableView];
    self.mineTableView.dataSource = self;
    self.mineTableView.delegate = self;
    [self.mineTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:mineCell];
    self.mineTableView.scrollsToTop = NO;
    
   self.mineTableView.showsHorizontalScrollIndicator = NO;
    self.mineTableView.showsVerticalScrollIndicator = NO;
    //self.mineTableView.bounces = NO;
    
    [self setUpheaderView];
    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificationAction:) name:LeaveTopNotificationName object:nil];
    self.canScroll = YES;// 默认是可以滚动的
    
    //接收跳转的id
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hotColumnPush:) name:@"hotColumnPush" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(postPush:) name:@"postPush" object:nil];
    
    
    
    // Do any additional setup after loading the view.
}
//创建头视图
-(void)setUpheaderView{
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, headerHeight)];
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.mineTableView.tableHeaderView = self.headerView;

    self.bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, headerHeight)];
    self.bgImageView.image = [UIImage imageNamed:@"me_profilebackground@2x.jpg"];
    self.bgImageView.userInteractionEnabled = YES;
    [self.headerView addSubview:self.bgImageView];
    
    self.userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    self.userImageView.image = [UIImage imageNamed:@"me_avatarplaceholder_75x75_@2x"];
    self.userImageView.layer.masksToBounds = YES;
    self.userImageView.layer.cornerRadius = 30;
    self.userImageView.center = self.headerView.center;
    self.userImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.userImageView addGestureRecognizer:tap];
     [self.headerView addSubview:self.userImageView];
    self.userImageView.hidden = YES;
    
    self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.userImageView.frame.origin.x, CGRectGetMaxY(self.userImageView.frame) + 2, CGRectGetWidth(self.userImageView.frame), 20)];
    self.userNameLabel.textColor = [UIColor whiteColor];
    [self.headerView addSubview:self.userNameLabel];
   // self.userNameLabel.backgroundColor = [UIColor yellowColor];
    self.userNameLabel.adjustsFontSizeToFitWidth = YES;
    self.userNameLabel.textAlignment = NSTextAlignmentCenter;
    
    
    self.accountButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.accountButton.frame = CGRectMake(self.userImageView.frame.origin.x, CGRectGetMaxY(self.userNameLabel.frame) + 2, CGRectGetWidth(self.userImageView.frame), 20);
   // [self.accountButton setTitle:@"登录" forState: UIControlStateNormal];
    [self.accountButton setTitleColor:[UIColor whiteColor] forState: UIControlStateNormal];
    [self.headerView addSubview:self.accountButton];
    [self.accountButton addTarget:self action:@selector(accountButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *login = [user objectForKey:@"status"];
    if ([login isEqualToString:@"yes"]) {
       // [self.accountButton setTitle:@"注销" forState:UIControlStateNormal];
  
        NSString *name = [user objectForKey:@"userName"];
        //self.userNameLabel.text = name;
        if ([user objectForKey:@"userIcon"]) {
            [self.userImageView sd_setImageWithURL:[NSURL URLWithString:[user objectForKey:@"userIcon"]]];
            
        }
        
        
   //获取喜欢的礼物的数组
        
        NSArray *hotModelArray = [NSArray arrayWithArray:[[DataFMDBHandle shareDataFMDBHandle] selecthotColumn:name WithModelOrNot:YES]];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hotcollData" object:hotModelArray];

      
        NSArray *giftArray = [NSArray arrayWithArray:[[DataFMDBHandle shareDataFMDBHandle] selectPrsent:name WithModelOrNot:YES]];
        
       [[NSNotificationCenter defaultCenter] postNotificationName:@"giftTableViewData" object:giftArray];
        
        
        

        
    } else {
  self.userImageView.image = [UIImage imageNamed:@"me_avatarplaceholder_75x75_@2x"];
       // [self.accountButton setTitle:@"登录" forState:UIControlStateNormal];
        
    }

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (buttonIndex == 1) {
//        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//        NSString *string = @"no";
//        [user setObject:string forKey:@"status"];
//        [user synchronize];
//        [self.accountButton setTitle:@"登录" forState:UIControlStateNormal];
//         self.userNameLabel.text = @"";
//        self.userImageView.image = [UIImage imageNamed:@"me_avatarplaceholder_75x75_@2x"];
//        
//    }
}

//跳转到礼物详情
-(void)hotColumnPush:(NSNotification *)notification{
    HotDeatilViewController *hotDVC = [[HotDeatilViewController alloc] init];
    hotDVC.dataId = [notification object];
    hotDVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:hotDVC animated:YES];

}

//跳转到攻略详情
-(void)postPush:(NSNotification *)notification{
    SelectDetailViewController *selectDetailVC = [[SelectDetailViewController alloc] init];
    selectDetailVC.dataId = [notification object];
    selectDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:selectDetailVC animated:YES];

}




-(void)tapAction:(UITapGestureRecognizer *)tap{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"status"] isEqualToString:@"yes"]) {
    
        
    } else {
      [self accountButtonAction:self.accountButton];
    }
    
}

-(void)accountButtonAction:(UIButton *)button{
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSString *login = [user objectForKey:@"status"];
//    if ([login isEqualToString:@"yes"]) {
//        [self.accountButton setTitle:@"注销" forState:UIControlStateNormal];
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否确认注销" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
//        alert.delegate = self;
//        [alert show];
//   
//    } else {
//    
//        [self.accountButton setTitle:@"登录" forState:UIControlStateNormal];
//        
//        LoginViewController *loginVC = [[LoginViewController alloc] init];
//        [self presentViewController:loginVC animated:YES completion:^{
//            
//            
//        }];
//        
//        
//    }
}

-(void)rightBarButtonAction{
    OptionViewController *optionVC = [[OptionViewController alloc] init];
    optionVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:optionVC animated:YES];
}



// 小Tableview告诉大Tableview可以滚动了
-(void)notificationAction:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        _canScroll = YES;
    }

}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mineCell];
    if (indexPath.section == 0) {
        TitleViewController *titleVC = [[TitleViewController alloc] init];
        [self addChildViewController:titleVC];
        [cell.contentView addSubview:titleVC.view];
    }
    
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = CGRectGetHeight(self.view.frame);
    
    return height;
}

// 主要逻辑:
// 当滑动一个Tableview时,两个Tableview同时会动,我们要做的是什么时候让大的动,什么时候让小的动
// 刚开始滑动两个一起动,当滑动到标题位置的时候,让大的保持在这个位置,发出通知让小的继续动
// 当小的往下滑动,滑动到偏移量为(0,0)点的时候,让小的保持在这个位置.并发出通知让大的开始动.

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    // 获得到第0section的位置
    
    CGFloat tabOffsetY = [self.mineTableView rectForSection:0].origin.y;
    CGFloat offsetY = scrollView.contentOffset.y;
   
    CGRect frame = self.bgImageView.frame;
    frame.origin.y = -offsetY;
//    NSLog(@"%.2f",offsetY);
    frame.size.height = offsetY + headerHeight;
    
    if (offsetY <= 0) {
        frame.origin.y = offsetY;
        frame.size.height = -offsetY + headerHeight;
    }
    
    self.bgImageView.frame = frame;
    
   // NSLog(@"====%f    %f",offsetY,tabOffsetY);
    // 如果偏移的距离大于等于section所在的位置,则不让大Tableview滑动了
    if (offsetY >= tabOffsetY) {
        // 往上滑动时不让大的滑动 让大的保持在tabOffsetY的位置 置顶位置
        scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        // 通知小的滑动
        [[NSNotificationCenter defaultCenter] postNotificationName:GoTopNotificationName object:nil userInfo:@{@"canScroll":@"1"}];
        _canScroll = NO;//大的不让滚动
    }else{
        //向下滑动时,保持大的不动
        // 下面判断是保持大的不动,因为往下拉的时候两个也是一起动,什么时候让大的动,就是在小的滑动偏移量为(0,0)时,小的发出通知
        if (!_canScroll) {
            scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        }
        
    }
  
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
